﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace MergeHosts
{
    public class MergeFacade
    {
        static string ipHostPattern = @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(.+)";

        public static void Merge(MergeData mergeData)
        {
            IMergeHosts mergeWorker = MergeHostsFactory.Create(mergeData);
            mergeWorker.Merge(mergeData.OldFilePath, mergeData.NewFilePath);
        }

        public static void WriteHosts(string filePath, Dictionary<string, string> mapping)
        {
            StreamWriter sw = new StreamWriter(filePath);
            foreach (KeyValuePair<string, string> pair in mapping)
            {
                sw.WriteLine(pair.Value + "    " + pair.Key);
            }
            sw.Close();
        }

        public static Dictionary<string, string> GetIpHostMapping(string filePath)
        {
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            if (File.Exists(filePath))
            {
                StreamReader sr = new StreamReader(filePath);
                while (!sr.EndOfStream)
                {
                    string s = sr.ReadLine().Trim();
                    Match m = Regex.Match(s, ipHostPattern);
                    if (m.Success)
                    {
                        if (mapping.ContainsKey(m.Groups[2].Value))
                        {
                            mapping[m.Groups[2].Value] = m.Groups[1].Value;
                        }
                        else
                        {
                            mapping.Add(m.Groups[2].Value, m.Groups[1].Value);
                        }
                    }
                }
                sr.Close();
            }
            return mapping;
        }
    }
}
